package com.le.tester.imooc.masterJUC.lock.reentrantlock;


import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：演示公平锁和非公平锁
 */
public class FairLock {
    public static void main(String[] args) {
        PrintQueue printQueue = new PrintQueue();
        Thread[] thread = new Thread[10];
        for (int i = 0; i < 10; i++) {
            thread[i] = new Thread(new Job(printQueue));
        }
        for (int i = 0; i < 10; i++) {
            //休眠，保证顺序
            thread[i].start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class PrintQueue {
        //使用公平锁
        private static ReentrantLock lock = new ReentrantLock(true);

        public static void printObj(Object doc) {
            lock.lock();
            try {
                long duration = new Random().nextInt(10) + 1;
                System.out.println(Thread.currentThread().getName() + " 正在打印，需要：" + duration  + "秒");
                //公平锁的打印
                Thread.sleep(duration);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            lock.lock();
            try {
                long duration = new Random().nextInt(10) + 1;
                System.out.println(Thread.currentThread().getName() + " 正在打印，需要：" + duration + "秒");
                //公平锁的打印
                Thread.sleep(duration);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

class Job implements Runnable {

    FairLock.PrintQueue printQueue;

    public Job(FairLock.PrintQueue printQueue) {
        this.printQueue = printQueue;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始打印");
        FairLock.PrintQueue.printObj(new Object());
        System.out.println(Thread.currentThread().getName() + "打印完毕");
    }
}
